//
//  HMStatusListViewModel.swift
//  MyWeibo


//  Created by apple on 16/4/20.
//  Copyright © 2016年 apple. All rights reserved.
//  当前viewModel对应的View是 HMHomeTableViewController
//  专门用于负责加载 首页控制器的数据，进行字典转模型


import UIKit
import SDWebImage

class HMStatusListViewModel: NSObject {
    
    //创建一个模型类型的数组保存数据
    //    var statusArray:[HMStatus]?
    var statusArray:[HMStatusViewModel]?
    
    
    //加载数据
    func loadData(isPullup:Bool,finished:(isSuccess:Bool)->()){
        
        //定义请求地址
        let urlString = "https://api.weibo.com/2/statuses/home_timeline.json"
        
        //请求
        var max_id:Int64 = 0
        
        //代表上拉加载
        if isPullup {
            //赋值id
            max_id = statusArray?.last?.status?.id ?? 0
            
            if max_id == 0 {
                
                max_id--
            }
            
        }else{
            
        }
        
        //定义请求参数  accesstonken
        let part = [
            
            "access_token" : HMUserAccountViewModel.sharedViewModel.accessToken ?? "",
            "max_id": "\(max_id)"
        ]
        //发送请求
        HMNetworkTools.sharedTools.request(urlString: urlString, parameters: part) { (responseObject, error) -> () in
            
            if error != nil {
                return
            }
            
            //            print(responseObject)
            //得到返回数据responseObject
            
            guard let responseDicts = responseObject as? [String: AnyObject] else{
                
                finished(isSuccess: false)
                print("返回的数据不是字典")
                
                return
            }
            
            // 1. 取出 statuses 对应该节点的数据 （字典数组）
            
            guard let dicts = responseDicts["statuses"] as? [[String:AnyObject]] else{
                
                print("取出的数据有误")
                return
            }
            
            //遍历数组转模型
            
            //创建一个viewmodel空数组存储数据
            var tempArray = [HMStatusViewModel]()
            
            //遍历数组
            for value in dicts {
                
                //取出模型 存进数组
                let status = HMStatus(dicts: value)
                
                //初始化一个viewmodel
                let viewModel = HMStatusViewModel()
                //设置模型到status里面去
                viewModel.status = status
                
                tempArray.append(viewModel)
                
            }
            //self.statusArray = tempArray
            
            //判断是否为空 实例化
            if self.statusArray == nil{
                
                self.statusArray = [HMStatusViewModel]()
                
            }
            
            //判断是否 上拉加载
            if isPullup {
                
                self.statusArray = self.statusArray! + tempArray
                
            }else{
                
                self.statusArray = tempArray + self.statusArray!
            }
            
            
            //加载完数据刷新数据
            //            finished(isSuccess: true)
            
            //缓存单张图片
            self.cachSingleImage(tempArray, finished: finished)
            
        }
    }
    
    //创建方法缓存单张图片  把数组传进来 在创建一个闭包通知下载完成
    private func cachSingleImage(array : [HMStatusViewModel] ,finished:(isSuccess:Bool)->()){
        
        //创建一个组
        
        let group = dispatch_group_create()
        
        //遍历加载数据
        
        for value in array {
            
            //取出图片数据
            let originalPicUrls = value.status?.pic_urls
            let retweetPicurls = value.status?.retweeted_status?.pic_urls
            
            //取到图片数组 原创和转发里面不会同时都有图片 所以
            let picUrls = ( originalPicUrls == nil || originalPicUrls!.count == 0 ) ? retweetPicurls : originalPicUrls
            
            //判断取出图片
            if picUrls?.count == 1 {
                
                //取到下载地址
                let url = picUrls?.first?.thumbnail_pic
                
                //添加到组中
                dispatch_group_enter(group)
                
                //下载图片
                SDWebImageManager.sharedManager().downloadImageWithURL(NSURL(string: url ?? ""), options: [], progress: nil, completed: { (image, error, _, _, _) -> Void in
                    
                    //更新单张图片的大小
                    value.updateSingleImagePictureViewSize()
                    //调度出组
                    
                    dispatch_group_leave(group)
                })
                
                
                
            }
            
        }
        
        //单张图片下载完成后回调闭包发出通知
        dispatch_group_notify(group, dispatch_get_main_queue()) { () -> Void in
            
            //回调闭包刷新
            finished(isSuccess: true)
            
        }
        
    }
}
